package edu.je.patent.service;

import com.junqson.je.common.model.ApiResult;
import edu.je.patent.model.PantentModel;
import edu.je.patent.model.Vo.MapToVo;
import edu.je.patent.repo.PantentRepo;
import edu.je.patent.util.PageUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.*;


/**
 * @author MengXin
 * @description:
 * @program: je-gateway
 * @date 2021/4/24 19:48
 * @mail mx@radish.cloud
 */
@Service
public class PattenService {
    @Autowired
    public PantentRepo pantentRepo;

    /**
     * @param oid id
	 * @param title 标题
	 * @param applyTime 申请时间
	 * @param applicant 申请人
	 * @param abstractInfo 摘要
	 * @param country 国家
     * @return edu.je.patent.model.PantentModel
     * @author Mengxin
     * @describe: 新增专利
     * @date 2021/4/26 5:19
     */
    public PantentModel addPantent(
            String oid,String title,String country,String applyTime,String applicant,String abstractInfo,Date publiseTime) {
        PantentModel PantentModel = new PantentModel();
        PantentModel.setApplicant(applicant);
        PantentModel.setApplytime(applyTime);
        PantentModel.setAbstractInfo(abstractInfo);
        PantentModel.setOid(oid);
        PantentModel.setPublishtime(publiseTime);
        PantentModel.setCountry(country);
        PantentModel.setPrefenceNumber(1);
        PantentModel.setPublishuserid(1L);
        PantentModel.setTitle(title);
        pantentRepo.save(PantentModel);
        return PantentModel;
    }

    /**
     * @param id id
     * @return edu.je.patent.model.PantentModel
     * @author Mengxin
     * @describe: 查询单条数据
     * @date 2021/4/26 5:37
     */
    public PantentModel getPantentById(Long id){
        return pantentRepo.findById(id).get();
    }

    /**
     * @param stime 开始时间
	 * @param etime 结束时间
     * @return java.util.List<edu.je.patent.model.Vo.MapToVo>
     * @author Mengxin
     * @describe: 统计国家信息
     * @date 2021/4/26 5:19
     */
    public List<MapToVo> getAllcountry(Date stime, Date etime) {
        List<PantentModel> pantentModelList = serach(stime, etime);
        List<String> strings = new ArrayList<>();
        for (PantentModel pa : pantentModelList) {
            strings.add(pa.getCountry());
        }
        return getMapToVos(strings);
    }

    /**
     * @param stime 开始日期
	 * @param etime 结束日期
     * @return java.util.List<edu.je.patent.model.Vo.MapToVo>
     * @author Mengxin
     * @describe: 获取申请人信息
     * @date 2021/4/26 5:19
     */
    public List<MapToVo> getApplicant(Date stime, Date etime) {
        List<PantentModel> pantentModelList = serach(stime, etime);
        List<String> strings = new ArrayList<>();
        for (PantentModel pa : pantentModelList) {
            strings.add(pa.getApplicant());
        }
        return getMapToVos(strings);
    }

    /**
     * @param strings 待统计词组
     * @return java.util.List<edu.je.patent.model.Vo.MapToVo>
     * @author Mengxin
     * @describe: 词频统计
     * @date 2021/4/26 5:19
     */
    private List<MapToVo> getMapToVos(List<String> strings) {
        Map<String, Integer> map = new HashMap<>();
        for (String s : strings) {
            if (StringUtils.isNotBlank(s)) {
                if (!map.containsKey(s)) {
                    map.put(s, 1);
                } else {
                    map.put(s, map.get(s) + 1);
                }
            }
        }
        List<MapToVo> list = new ArrayList<>();
        map.forEach((key, value) -> {
            list.add(new MapToVo(key, value));
        });
        return list;
    }

    /**
     * @param PantentModel 查询对象
	 * @param pageable 分页
     * @return org.springframework.data.domain.Page<edu.je.patent.model.PantentModel>
     * @author Mengxin
     * @describe: 多条件查询
     * @date 2021/4/26 5:20
     */
    public Page<PantentModel> getPantentByDao(PantentModel PantentModel, Pageable pageable) {
        Assert.notNull(PantentModel);

        Page<PantentModel> result = pantentRepo.findAll((Specification<PantentModel>) (root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();

            if (StringUtils.isNotBlank(PantentModel.getTitle())) {
                list.add(criteriaBuilder.like(root.get("title").as(String.class), "%" + PantentModel.getTitle() + "%"));
            }
            if (StringUtils.isNotBlank(PantentModel.getOid())) {
                list.add(criteriaBuilder.like(root.get("oid").as(String.class), "%" + PantentModel.getOid() + "%"));
            }

            if (StringUtils.isNotBlank(PantentModel.getApplicant())) {
                list.add(criteriaBuilder.like(root.get("applicant").as(String.class), "%" + PantentModel.getApplicant() + "%"));
            }
            if ( StringUtils.isNotBlank(PantentModel.getCountry())) {
                list.add(criteriaBuilder.equal(root.get("country").as(String.class), PantentModel.getCountry()));

            }
            if (StringUtils.isNotBlank(PantentModel.getAbstractInfo())) {
                list.add(criteriaBuilder.like(root.get("AbstractInfo").as(String.class), "%" + PantentModel.getAbstractInfo() + "%"));
            }
            if (PantentModel.getPid()!=null) {
                list.add(criteriaBuilder.equal(root.get("pid").as(Long.class),  PantentModel.getPid() ));
            }

            Predicate[] p = new Predicate[list.size()];
            return criteriaBuilder.or(list.toArray(p));
        }, pageable);
        return result;
    }


    public List<PantentModel> getAll(Integer page,Integer size){
        return pantentRepo.findAll(PageUtil.getPageable(page, size)).getContent();
    }


    /**
     * @param stime 开始时间
	 * @param etime 结束时间
     * @return java.util.List<edu.je.patent.model.PantentModel>
     * @author Mengxin
     * @describe: 按时间段查询
     * @date 2021/4/26 5:25
     */
    public List<PantentModel> serach(Date stime, Date etime) {
        List<PantentModel> resultList = null;
        Specification<PantentModel> querySpecifi = new Specification<PantentModel>() {
            @Override
            public Predicate toPredicate(Root<PantentModel> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder cb) {
                List<Predicate> predicates = new ArrayList<>();
                if (StringUtils.isNotBlank(String.valueOf(stime))) {
                    //大于或等于传入时间

                    predicates.add(cb.greaterThanOrEqualTo(root.get("publishtime").as(Date.class), stime));
                }
                if (StringUtils.isNotBlank(String.valueOf(etime))) {
                    //小于或等于传入时间
                    predicates.add(cb.lessThanOrEqualTo(root.get("publishtime").as(Date.class), etime));
                }
                // and到一起的话所有条件就是且关系，or就是或关系
                return cb.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };
        resultList = this.pantentRepo.findAll(querySpecifi);
        return resultList;

    }

    public List<PantentModel> serachTime(Long lessMonth, Long moreMonth) {
        List<PantentModel> resultList = null;
        Specification<PantentModel> querySpecifi = new Specification<PantentModel>() {
            @Override
            public Predicate toPredicate(Root<PantentModel> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder cb) {
                List<Predicate> predicates = new ArrayList<>();
                if (StringUtils.isNotBlank(String.valueOf(lessMonth))) {
                    //大于或等于传入时间
                    predicates.add(cb.greaterThanOrEqualTo(root.get("publishuserid").as(Long.class), lessMonth));
                }
                if (StringUtils.isNotBlank(String.valueOf(moreMonth))) {
                    //小于或等于传入时间
                    predicates.add(cb.lessThanOrEqualTo(root.get("publishuserid").as(Long.class), moreMonth));
                }
                // and到一起的话所有条件就是且关系，or就是或关系
                return cb.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };
        resultList = this.pantentRepo.findAll(querySpecifi);
        return resultList;
    }


    public PantentModel deletePaten(Long id){
        Optional<PantentModel> model = pantentRepo.findById(id);
        if (model.isPresent()){
            pantentRepo.delete(model.get());
            return model.get();
        }else {
            return null;
        }
    }


}
